const gulp = require('gulp'),
	htmlmin = require('gulp-htmlmin'),
	cleanCss = require('gulp-clean-css'),
	autoPrefixer = require('gulp-autoprefixer'),
	uglify = require('gulp-uglify'),
	babel = require('gulp-babel'),
	del = require('del'),
	connect = require('gulp-connect'),
	// 引入包的同时直接解构出来使用
	{ createProxyMiddleware } = require('http-proxy-middleware')
	sass = require('gulp-sass')
	
const paths = {
	html:{
		src:'src/**/*.html',
		dest:'dist'
	},
	css:{
		src:'src/css/**/*.scss',
		dest:'dist/css'
	},
	js:{
		src:'src/js/**/*.js',
		dest:'dist/js'
	},
	imgs:{
		src:'src/imgs/**',
		dest:'dist/imgs'
	},
	libs:{
		src:'src/libs/**',
		dest:'dist/libs'
	},
	ico:{
		src:'src/ico/**/*',
		dest:'dist/ico'
	}
}	

//制定一个HTML任务
const html = ()=>{
	return gulp.src(paths.html.src)
	.pipe(htmlmin({
		removeComments: true,//清除HTML注释
		collapseWhitespace: true,//压缩HTML
		collapseBooleanAttributes: true,//省略布尔属性的值 <input checked="true"/> ==> <input checked />
		removeEmptyAttributes: true,//删除所有空格作属性值 <input id="" /> ==> <input />
		removeScriptTypeAttributes: false,//删除<script>的type="text/javascript"
		removeStyleLinkTypeAttributes: true,//删除<style>和<link>的type="text/css"
		minifyJS: true,//压缩页面JS
		minifyCSS: true//压缩页面CSS 
	}
	))
	.pipe(gulp.dest(paths.html.dest))
	.pipe(connect.reload())
}

//制定一个css任务:先把sass转成css，再放到dist里面去
const css = ()=>{
	return gulp.src(paths.css.src)
	.pipe(sass())
	.pipe(autoPrefixer({
		cascade:false
	}))
	.pipe(cleanCss())
	.pipe(gulp.dest(paths.css.dest))
	.pipe(connect.reload())
}

//制定一个js任务
const js = ()=>{
	return gulp.src(paths.js.src)
	.pipe(babel({
		presets: ['@babel/env']
	}))
	.pipe(uglify())
	.pipe(gulp.dest(paths.js.dest))
	.pipe(connect.reload())
}

//制定一个imgs任务
const imgs = ()=>{
	return gulp.src(paths.imgs.src)
	.pipe(gulp.dest(paths.imgs.dest))
}

//制定一个libs任务
const libs = ()=>{
	return gulp.src(paths.libs.src)
	.pipe(gulp.dest(paths.libs.dest))
}


//制定一个删除任务
const delDist = ()=>{
	return del('dist')
}

//制定一个server任务：建立一个本地服务器
const server = ()=>{
	connect.server({
		root:'dist',
		port:5200,
		livereload:true,
		middleware(){
			return [
				//把前端以api开头的请求代理到拼多多
				createProxyMiddleware('/rest',{
					target:'https://china.coach.com',
					changeOrigin:true
				})
			]
		}	
	})
}

//watch 监听文件改变，文件改变而重启相应的任务
const watch = ()=>{
	gulp.watch(paths.html.src,html)
	gulp.watch(paths.js.src,js)
	gulp.watch(paths.css.src,css)
}

const ico = ()=>{
	return gulp.src(paths.ico.src)
	.pipe(gulp.dest(paths.ico.dest))
}

//只导出default一个任务，在这个任务里异步执行所有任务
module.exports.default =gulp.series(delDist,gulp.parallel(html,css,js,imgs,libs,server,watch,ico))
 